package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 添加文章
func AddArticle(c *gin.Context) {}

// 查询分类文章
func GetCateArticle(c *gin.Context) {
	// strconv.Atoi 字符串转换成 int
	id, _ := strconv.Atoi(c.Param("id"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}

	if pageNum == 0 {
		pageNum = 1
	}

	cateArticleList, total := model.GetCateArticle(id, pageSize, pageNum)
	fmt.Println("articleList", cateArticleList)
	fmt.Println("total", total)
	if cateArticleList == nil {
		code := errmsg.ERROR_CATE_NOT_EXIST
		c.JSON(http.StatusNotFound, gin.H{
			"status":  code,
			"data":    cateArticleList,
			"total":   total,
			"message": errmsg.GetErrMsg(code),
		})
	}
	code = errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    cateArticleList,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})

}

// 查询单个文章
func GetArticleInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	article, code := model.GetArticleInfo(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    article,
		"total":   1,
		"message": errmsg.GetErrMsg(code),
	})

}

// 查询文章列表
func GetArticleList(c *gin.Context) {
	// strconv.Atoi 字符串转换成 int
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}

	if pageNum == 0 {
		pageNum = 1
	}

	//if pageSize == 0 {
	//	pageSize = -1 //因gorm提供 一个方法
	//}
	//if pageNum == 0 {
	//	pageNum = -1 //因gorm提供 一个方法
	//}
	articleList, total := model.GetArticleList(pageSize, pageNum)
	fmt.Println("articleList", articleList)
	fmt.Println("total", total)
	code = errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    articleList,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})

}

// 修改文章
func EditArticle(c *gin.Context) {}

// 删除文章
func DeleteArticle(c *gin.Context) {}
